<script setup lang="tsx">
import MultiGraphView from './views/MultiGraphView.vue'
import SingleGraphView from './views/SingleGraphView.vue'
import HeaderBar from './components/HeaderBar.vue'
import { onMounted, ref, watch } from 'vue'

import { editorState, disableContextmenu, listenerShortcutKey } from './mixins/useEditorState'

import { debounce } from 'lodash-unified'
import { message } from 'ant-design-vue'
const editorEl = ref<{ $el: HTMLElement }>()

const props = withDefaults(defineProps<{ debug: boolean }>(), {
  debug: false
})

const handleAutoSave = debounce(() => {
  if (editorState.doneGuide) {
    console.log('自动保存')
    const blob = new Blob([JSON.stringify(editorState.configState, null, 2)], { type: 'application/json' })
    const file = new File([blob], `${new Date().getTime()}.json`, { type: 'application/json' })
    const formData = new FormData()
    formData.append('file', file)
    message.destroy()
    message.loading('自动保存中', 0)
    fetch('http://192.168.2.6:7001/api/v1/auto-save', {
      method: 'POST',
      body: formData
    })
      .then((response) => response.json())
      .then(() => {
        setTimeout(() => {
          message.destroy()
          message.success('保存成功')
        }, 500)
      })
      .catch(() => {
        setTimeout(() => {
          message.destroy()
          message.error('保存失败')
        }, 500)
      })
  }
}, 800)

watch(() => editorState.configState, handleAutoSave, {
  deep: true
})

onMounted(() => {
  editorState.debug = props.debug
  disableContextmenu(editorEl.value?.$el)
  listenerShortcutKey()
})
</script>
<template>
  <a-layout ref="editorEl" class="h5-editor">
    <HeaderBar></HeaderBar>
    <a-layout class="h5-editor__layout h5-editor__content">
      <MultiGraphView v-if="editorState?.multiGraph" />
      <SingleGraphView v-else />
    </a-layout>
  </a-layout>
</template>

<style lang="less">
@import './styles/default.less';
</style>
